package cn.lds.j375.chlm.controller;

import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.Menu;
import cn.lds.j375.chlm.exception.ChlmException;
import cn.lds.j375.chlm.mapper.MenuMapper;
import cn.lds.j375.chlm.serivce.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    private Logger log = LoggerFactory.getLogger(MenuController.class);

    @RequestMapping("/show_menu")
    public String showMenu(Model model) throws ChlmException {
        ResultDTO<List<Menu>> resultDTO = menuService.selectMenuAll();
        model.addAttribute("result",resultDTO);
        return "show_menu";
    }

    @RequestMapping("/add_menu")
    public String addMenu(){
        return "add_menu";
    }

    @RequestMapping(value = "do_add_menu",method = RequestMethod.POST)
    public String doAddMenu(Menu menu, MultipartFile menuImg, HttpServletRequest request) throws IOException, ChlmException {

        String realPath = request.getServletContext().getRealPath("/uploads");

        File file = new File(realPath);

        if (!file.exists()){
            file.mkdir();
        }

        String originalFilename = menuImg.getOriginalFilename();

        String replace = UUID.randomUUID().toString().replace("-", "");

        String fileName = replace + "-" + originalFilename;

        menuImg.transferTo(new File(realPath,fileName));

        menu.setMenuImgUrl("/uploads/" + fileName);

        log.info("menu:{}",menu);

        ResultDTO resultDTO = menuService.addMenu(menu);

        log.info("result:{}",resultDTO);

        return "home";
    }
}
